// 首页 reducer
import { HomeAction } from '@/types/store'
import { Articles, Channel } from '@/types/data'
import { sortBy } from 'lodash'
// 定义 home state类型
type HomeState = {
  channels: Channel[]
  restChannel: Channel[]
  channelActiveKey: number // 添加频道选择对应状态
  channelArticles: {
    [key in number]: Articles
  }
}
// 初始化 state
const initialState: HomeState = {
  // 我的频道
  channels: [],
  // 剩余频道（推荐频道）
  restChannel: [],
  // 选中频道id
  channelActiveKey: 0,
  // 频道对应文章列表
  channelArticles: {}, // 默认为空
}

export const home = (state = initialState, action: HomeAction): HomeState => {
  if (action.type === '/home/getChannels') {
    return {
      ...state,
      channels: action.payload,
    }
  }

  if (action.type === '/home/getRestChannel') {
    return {
      ...state,
      restChannel: action.payload,
    }
  }
  if (action.type === 'home/toggleChannel') {
    return {
      ...state,
      channelActiveKey: action.payload,
    }
  }
  if (action.type === 'home/delMyChannel') {
    return {
      ...state,
      // 用户频道中的直接删除
      channels: state.channels.filter((item) => item.id !== action.payload.id),
      // 推荐频道加进来
      // restChannel: [...state.restChannel, action.payload],
      // 优化：将被删除频道添加到推荐频道中，并且根据 id 进行排序
      // restChannel: sortBy([...state.restChannel, action.payload], 'id'),
      // 数组原生排序方法？还记得不？
      // a-b 升序 b-a 降序
      restChannel: [...state.restChannel, action.payload].sort(
        (a, b) => a.id - b.id
      ),
    }
  }
  if (action.type === 'home/addChannel') {
    return {
      ...state,
      // 用户频道中追加到末尾
      channels: sortBy([...state.channels, action.payload], 'id'), // 优化，排序
      // 推荐频道中删除
      restChannel: state.restChannel.filter(
        (item) => item.id !== action.payload.id
      ),
    }
  }
  if (action.type === 'home/getArticleList') {
    // 新来的数据:频道和文章列表
    const channelId = action.payload.channelId
    const newArticles = action.payload.articles
    const currentArticles = state.channelArticles[channelId] || {
      pre_timestamp: Date.now(),
      results: [],
    }
    return {
      ...state,
      channelArticles: {
        // 先把原来的数据赋值一遍
        ...state.channelArticles,
        // 在原来的频道基础上，追加这次请求回来频道的数据
        [channelId]: {
          // 时间戳更新位最后一次请求成功的时间戳
          pre_timestamp: newArticles.pre_timestamp,
          // 当前频道数据 + 新来的数据
          results: [...currentArticles.results, ...newArticles.results],
        },
      },
    }
  }
  return state
}
